<template>
	<cmDialog v-model="dialogState" :modal-title="props.editId == '' ? '新增' : props.isView ? '详情' : '编辑'" model-width="1000px">
		<el-form ref="baseFormRef" :model="baseForm" :rules="props.isView ? rules : baseRules" label-width="200px">
			<el-tabs v-model="activeName" class="tabs" @tab-click="handleClick">
				<el-tab-pane label="基础信息" name="base">
					<div class="content">
						<el-row>
							<el-col :span="12">
								<el-form-item label="项目名称" prop="standardProjectInfo.standardProjectName">
									<el-input
										v-model="baseForm.standardProjectInfo.standardProjectName"
										placeholder="请输入"
										:disabled="props.isAudit ? shenheDisabled : shenbaoDisabled"
									/>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="申请年份" prop="standardProjectInfo.applyYear">
									<el-date-picker
										v-model="baseForm.standardProjectInfo.applyYear"
										type="year"
										format="YYYY"
										value-format="YYYY"
										placeholder="请选择"
										:disabled="props.isAudit ? shenheDisabled : shenbaoDisabled"
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="12">
								<el-form-item label="自筹经费(万元)" prop="standardProjectInfo.projectSelfFunding">
									<el-input
										v-model="baseForm.standardProjectInfo.projectSelfFunding"
										placeholder="请输入"
										:disabled="props.isAudit ? shenheDisabled : shenbaoDisabled"
									/>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="申请经费(万元)" prop="standardProjectInfo.projectFunding">
									<el-input
										v-model="baseForm.standardProjectInfo.projectFunding"
										placeholder="请输入"
										:disabled="props.isAudit ? shenheDisabled : shenbaoDisabled"
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="12">
								<el-form-item label="主管部门(提出单位)名称" prop="standardProjectInfo.responsibleOrg">
									<!-- <el-select
										v-model="baseForm.standardProjectInfo.responsibleOrg"
										multiple
										:multiple-limit="3"
										placeholder="请选择"
										:disabled="props.isAudit ? shenheDisabled : shenbaoDisabled"
									>
										<el-option v-for="item in responsibleOrgArr" :key="item.id" :label="item.name" :value="item.code" />
									</el-select> -->
									<el-tree-select
										v-model="baseForm.standardProjectInfo.responsibleOrg"
										:data="responsibleOrgArr"
										highlight-current
										:props="{
											value: 'code',
											label: 'name',
											children: 'children'
										}"
										multiple
										clearable
									/>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="联系人姓名" prop="standardProjectInfo.contactName">
									<el-input
										v-model="baseForm.standardProjectInfo.contactName"
										placeholder="请输入"
										:disabled="props.isAudit ? shenheDisabled : shenbaoDisabled"
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="12">
								<el-form-item label="联系电话" prop="standardProjectInfo.contactTel">
									<el-input
										v-model="baseForm.standardProjectInfo.contactTel"
										placeholder="请输入"
										:disabled="props.isAudit ? shenheDisabled : shenbaoDisabled"
									/>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="联系地址" prop="standardProjectInfo.contactAddress">
									<el-input
										v-model="baseForm.standardProjectInfo.contactAddress"
										placeholder="请输入"
										:disabled="props.isAudit ? shenheDisabled : shenbaoDisabled"
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="12">
								<el-form-item label="联系邮箱" prop="standardProjectInfo.contactEmail">
									<el-input
										v-model="baseForm.standardProjectInfo.contactEmail"
										placeholder="请输入"
										:disabled="props.isAudit ? shenheDisabled : shenbaoDisabled"
									/>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="专业及重点领域划分" prop="standardProjectInfo.professionalKeyFields">
									<el-select
										v-model="baseForm.standardProjectInfo.professionalKeyFields"
										multiple
										placeholder="请选择"
										:disabled="props.isAudit ? shenheDisabled : shenbaoDisabled"
									>
										<el-option v-for="item in professionalKeyFieldsArr" :key="item.id" :label="item.name" :value="item.code" />
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row v-if="baseForm.projectDocument.length > 0">
							<el-col :span="12">
								<el-form-item label="立项批文">
									<span
										v-for="(item, index) in baseForm.projectDocument"
										:key="index"
										type="success"
										style="cursor: pointer; text-decoration: underline; display: block; margin-top: -10px; margin-right: 15px"
										@click="handleUploadPdfPreview(item)"
									>
										{{ item.fileRealName }}.{{ item.fileExtName }}
									</span>
								</el-form-item>
							</el-col>
						</el-row>
						<div class="add-unit">
							<div class="tit">主编单位</div>
							<el-button v-if="props.isAudit ? !shenheDisabled : !shenbaoDisabled" type="primary" @click="handleAddUnit">新增</el-button>
						</div>
						<el-table :data="unitList" style="width: 100%" border>
							<el-table-column label="次序" prop="orderName" width="110">
								<template #default="scope">
									{{ `第${scope.row.orderName}${scope.row.unitType == 0 ? '主编单位' : '参编单位'}` }}
								</template>
							</el-table-column>
							<el-table-column label="单位名称" prop="editorUnitName" width="120" align="center"></el-table-column>
							<el-table-column label="企业社会信用代码" prop="userCode" width="120" align="center"></el-table-column>
							<el-table-column label="联系人" prop="contacts" width="70" align="center"></el-table-column>
							<el-table-column label="联系电话(手机)" prop="contactsTel" width="120" align="center"></el-table-column>
							<el-table-column label="联系人邮箱" prop="contactsEmail" width="120" align="center"></el-table-column>
							<el-table-column label="联系地址" prop="contactsAddress" width="150" align="center"></el-table-column>
							<el-table-column label="负责人" prop="responsiblePerson" width="70" align="center"></el-table-column>
							<el-table-column label="负责人电话(手机或座机)" prop="responsiblePersonTel" width="120" align="center"></el-table-column>
							<el-table-column label="负责人邮箱" prop="responsiblePersonEmail" width="120" align="center"></el-table-column>
							<el-table-column v-if="props.isAudit ? !shenheDisabled : !shenbaoDisabled" label="操作" width="140" align="center" fixed="right">
								<template #default="scope">
									<!-- <el-button type="danger" size="small" @click="handleDeleteUnit(scope.$index)">删除</el-button>
									<el-button type="success" size="small" @click="handleEditUnit(scope.row, scope.$index)">编辑</el-button> -->
									<el-icon
										:size="16"
										color="#1491FF"
										title="编辑"
										style="cursor: pointer; margin: 0 6px"
										@click="handleEditUnit(scope.row, scope.$index)"
									>
										<Edit />
									</el-icon>
									<el-icon :size="16" color="#fe6360" title="删除" style="cursor: pointer; margin: 0 6px" @click="handleDeleteUnit(scope.$index)">
										<Delete />
									</el-icon>
								</template>
							</el-table-column>
						</el-table>
					</div>
				</el-tab-pane>
				<el-tab-pane label="项目建议书(填写版)" name="input">
					<div class="content">
						<el-row>
							<el-col :span="12">
								<el-form-item label="申报标准类别" prop="standardProjectProposal.standardCategory" class="custom-label">
									<el-radio-group
										v-model="baseForm.standardProjectProposal.standardCategory"
										:disabled="props.isAudit ? shenheDisabled : shenbaoDisabled"
									>
										<el-radio v-for="item in standardCategory" :key="item.id" :value="item.code">{{ item.name }}</el-radio>
									</el-radio-group>
								</el-form-item>
							</el-col>
							<el-col v-show="baseForm.standardProjectProposal.standardCategory == '1'" :span="12">
								<el-form-item label="原编号" prop="standardProjectProposal.originalNumber" class="custom-label">
									<el-input
										v-model="baseForm.standardProjectProposal.originalNumber"
										placeholder="请输入"
										:disabled="props.isAudit ? shenheDisabled : shenbaoDisabled"
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="12">
								<el-form-item label="申报标准类型" prop="standardProjectProposal.standardType" class="custom-label">
									<el-radio-group
										v-model="baseForm.standardProjectProposal.standardType"
										:disabled="props.isAudit ? shenheDisabled : shenbaoDisabled"
									>
										<el-radio v-for="item in standardType" :key="item.id" :value="item.code">{{ item.name }}</el-radio>
									</el-radio-group>
								</el-form-item>
							</el-col>
							<!-- <el-col :span="12">
                                <el-form-item label="参编单位" prop="standardProjectProposal.originalNumber"
                                    class="custom-label">
                                    <el-input v-model="baseForm.standardProjectProposal.originalNumber"
                                        placeholder="请输入" />
                                </el-form-item>
                            </el-col> -->
						</el-row>
						<el-row>
							<el-col :span="24">
								<el-form-item label="定制(修订)目的、意义以及经济效益和社会效益" prop="standardProjectProposal.setGoal">
									<el-input
										v-model="baseForm.standardProjectProposal.setGoal"
										type="textarea"
										:rows="3"
										placeholder="请输入"
										:disabled="props.isAudit ? shenheDisabled : shenbaoDisabled"
										maxlength="500"
										show-word-limit
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="24">
								<el-form-item label="与国家、行业及本市现行同类标准的关系" prop="standardProjectProposal.standardRelationship">
									<el-input
										v-model="baseForm.standardProjectProposal.standardRelationship"
										type="textarea"
										:rows="3"
										placeholder="请输入"
										:disabled="props.isAudit ? shenheDisabled : shenbaoDisabled"
										maxlength="500"
										show-word-limit
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="24">
								<el-form-item label="与国外先进标准技术内容对比" prop="standardProjectProposal.standardComparison">
									<el-input
										v-model="baseForm.standardProjectProposal.standardComparison"
										type="textarea"
										:rows="3"
										placeholder="请输入"
										:disabled="props.isAudit ? shenheDisabled : shenbaoDisabled"
										maxlength="500"
										show-word-limit
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="24">
								<el-form-item label="标准整合的相关建议(选填)" prop="standardProjectProposal.integrateSuggestions">
									<el-input
										v-model="baseForm.standardProjectProposal.integrateSuggestions"
										type="textarea"
										:rows="3"
										placeholder="请输入"
										:disabled="props.isAudit ? shenheDisabled : shenbaoDisabled"
										maxlength="500"
										show-word-limit
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="24">
								<el-form-item label="适用范围" prop="standardProjectProposal.scopeApplication">
									<el-input
										v-model="baseForm.standardProjectProposal.scopeApplication"
										type="textarea"
										:rows="3"
										placeholder="请输入"
										:disabled="props.isAudit ? shenheDisabled : shenbaoDisabled"
										maxlength="500"
										show-word-limit
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="24">
								<el-form-item label="主要技术内容" prop="standardProjectProposal.mainContent">
									<el-input
										v-model="baseForm.standardProjectProposal.mainContent"
										type="textarea"
										:rows="3"
										placeholder="请输入"
										:disabled="props.isAudit ? shenheDisabled : shenbaoDisabled"
										maxlength="500"
										show-word-limit
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="24">
								<el-form-item label="编制标准的技术条件和成熟程度及需进一步论证和试验的技术关键" prop="standardProjectProposal.keyTechnology">
									<el-input
										v-model="baseForm.standardProjectProposal.keyTechnology"
										type="textarea"
										:rows="3"
										placeholder="请输入"
										:disabled="props.isAudit ? shenheDisabled : shenbaoDisabled"
										maxlength="500"
										show-word-limit
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="24">
								<el-form-item label="编制时间安排" prop="standardProjectProposal.preparationSchedule">
									<el-input
										v-model="baseForm.standardProjectProposal.preparationSchedule"
										type="textarea"
										:rows="3"
										placeholder="请输入"
										:disabled="props.isAudit ? shenheDisabled : shenbaoDisabled"
										maxlength="500"
										show-word-limit
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="24">
								<el-form-item label="主编单位从事标准化工作情况介绍" prop="standardProjectProposal.editorUnitWorkSituation">
									<el-input
										v-model="baseForm.standardProjectProposal.editorUnitWorkSituation"
										type="textarea"
										:rows="3"
										placeholder="请输入"
										:disabled="props.isAudit ? shenheDisabled : shenbaoDisabled"
										maxlength="500"
										show-word-limit
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="24">
								<el-form-item label="项目负责人从事标准化工作情况介绍" prop="standardProjectProposal.responsiblePersonWorkSituation">
									<el-input
										v-model="baseForm.standardProjectProposal.responsiblePersonWorkSituation"
										type="textarea"
										:rows="3"
										placeholder="请输入"
										:disabled="props.isAudit ? shenheDisabled : shenbaoDisabled"
										maxlength="500"
										show-word-limit
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<div class="add-unit">
							<div class="tit">主要起草人</div>
							<el-button v-if="props.isAudit ? !shenheDisabled : !shenbaoDisabled" type="primary" @click="handleAddDrafter">新增</el-button>
						</div>
						<el-table :data="drafterList" style="width: 100%" border>
							<el-table-column type="index" label="序号" width="80" align="center" />
							<el-table-column label="姓名" prop="mainDrafterName" width="100" align="center" />
							<el-table-column label="职称/职务" prop="mainDrafterTitle" width="80" align="center" />
							<el-table-column label="单位" prop="mainDrafterCompany" align="center" />
							<el-table-column label="主要负责的章节或技术内容" prop="responsibleContent" align="center" />
							<el-table-column label="备注" prop="remark" align="center" />
							<el-table-column v-if="props.isAudit ? !shenheDisabled : !shenbaoDisabled" label="操作" width="140" align="center" fixed="right">
								<template #default="scope">
									<el-icon
										:size="16"
										color="#1491FF"
										title="编辑"
										style="cursor: pointer; margin: 0 6px"
										@click="handleEditDrafter(scope.row, scope.$index)"
									>
										<Edit />
									</el-icon>
									<el-icon :size="16" color="#f00" title="删除" style="cursor: pointer; margin: 0 6px" @click="handleDeleteDrafter(scope.$index)">
										<Delete />
									</el-icon>
								</template>
							</el-table-column>
						</el-table>
					</div>
				</el-tab-pane>
				<el-tab-pane label="项目建议书(盖章版pdf)" name="upload">
					<div class="content">
						<el-row>
							<el-col :span="12">
								<el-form-item label="项目建议书盖章版(pdf)" class="upload-item">
									<el-upload
										ref="uploadPdfRef"
										drag
										:action="uploadApi"
										:headers="uploadHeaders"
										:data="uploadData"
										accept=".pdf"
										:limit="1"
										:file-list="uploadShowPdfList"
										:on-exceed="handleExceed"
										:on-preview="handleUploadPdfPreview"
										:on-success="handleUploadPdfSuccess"
										:on-error="handleUploadPdfError"
										:on-remove="handleUploadPdfRemove"
										:before-upload="beforeUploadPdf"
										:disabled="shenbaoDdfUploadDisabled"
									>
										<el-icon class="el-icon--upload"><upload-filled /></el-icon>
										<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
									</el-upload>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="成果资料(pdf)" class="upload-item">
									<el-upload
										ref="uploadPdf1Ref"
										drag
										:action="uploadApi"
										:headers="uploadHeaders"
										:data="uploadData3"
										accept=".pdf"
										:limit="1"
										:file-list="uploadShowPdfList1"
										:on-exceed="handleExceed"
										:on-preview="handleUploadPdfPreview"
										:on-success="handleUploadPdfSuccess1"
										:on-error="handleUploadPdfError1"
										:on-remove="handleUploadPdfRemove1"
										:before-upload="beforeUploadPdf"
										:disabled="shenbaoDdfUploadDisabled"
									>
										<el-icon class="el-icon--upload"><upload-filled /></el-icon>
										<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
									</el-upload>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="24">
								<el-form-item label="其他资料" prop="standardProjectProposal.pdf">
									<el-upload
										class="upload-demo"
										drag
										:action="uploadApi"
										:headers="uploadHeaders"
										:data="uploadData2"
										:file-list="uploadShowList"
										:on-success="handleUploadSuccess"
										:on-error="handleUploadError"
										:on-remove="handleUploadRemove"
										:disabled="shenbaoDdfUploadDisabled"
										:on-preview="handleUploadPdfPreview"
									>
										<el-icon class="el-icon--upload"><upload-filled /></el-icon>
										<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
									</el-upload>
								</el-form-item>
							</el-col>
						</el-row>
					</div>
				</el-tab-pane>
				<el-tab-pane v-if="props.showAudit" label="审核意见" name="examine">
					<el-table :data="auditRecordList" style="width: 100%" border>
						<el-table-column label="审核主体" prop="shzt" align="center" />
						<el-table-column label="对申报标准意见" prop="remark" align="center">
							<template #default="scope">
								<div>{{ dictionaryStore.getDictionaryName('T013', scope.row.approvalStatus) }}</div>
								<div>{{ scope.row.remark }}</div>
							</template>
						</el-table-column>
						<el-table-column label="人员/时间" prop="userName" align="center">
							<template #default="scope">
								<div>{{ scope.row.userName.split('/')[0] }}</div>
								<div>{{ scope.row.userName.split('/')[1] }}</div>
							</template>
						</el-table-column>
						<el-table-column label="附件" prop="fileList" align="center">
							<template #default="scope">
								<div v-for="file in scope.row.fileList" :key="file.fileId" style="cursor: pointer" @click="handleUploadPdfPreview(file)">
									{{ file.fileRealName }}.{{ file.fileExtName }}
								</div>
							</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
			</el-tabs>
		</el-form>
		<template #footer>
			<div class="dialog-foot">
				<el-button v-if="!shenbaoDisabled" @click="saveTemp(1)">暂存</el-button>
				<el-button
					v-if="(activeName == 'input' || activeName == 'upload') && !props.isView && !shenbaoDisabled"
					type="primary"
					@click="submitForm(baseFormRef)"
					>提交</el-button
				>
				<el-button @click="closeModal">关闭</el-button>
				<el-button
					v-if="activeName == 'upload' && !props.isAudit && !shenbaoDdfUploadDisabled && Number(baseForm.standardProjectInfo.applyStage) > 1"
					type="primary"
					@click="saveUploadPdf"
					>保存</el-button
				>
				<el-button v-if="props.isAudit && activeName != 'examine'" type="primary" @click="submitForm(baseFormRef)">提交</el-button>
			</div>
		</template>
		<addUnit v-model="showAddUnit" :unit-count="unitCount" :unit-info="unitInfo" @submit-success="submitUnit" @close-dialog="closeUnitDialog" />
		<addDrafer v-model="showAddDrafter" :drafter-info="drafterInfo" @submit-success="submitDrafter" @close-dialog="closeDrafterDialog" />
	</cmDialog>
</template>
<script lang="ts" setup>
import { addDeclareTemp, getDeclare, saveDeclare, updateDeclareTemp } from '@/api/declare'
import { filePreviewByName } from '@/api/sys/upload'
import cmDialog from '@/components/cm-dialog/index.vue'
import { Drafter, Unit, UploadFile } from '@/interface/declare'
import { useDictionaryStore } from '@/store/modules/dictionary'
import { useUserStore } from '@/store/modules/user'
import type { FormInstance, TabsPaneContext, UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import addDrafer from './addDrafer.vue'
import addUnit from './addUnit.vue'

const dictionaryStore = useDictionaryStore()
const userStore = useUserStore()

const props = defineProps({
	modelValue: Boolean,
	editId: {
		type: String,
		default: ''
	},
	isView: Boolean,
	isAudit: {
		type: Boolean,
		default: false
	},
	showAudit: {
		type: Boolean,
		default: false
	}
})

const shenbaoDisabled = computed(
	() => props.isView || (baseForm.value.standardProjectInfo.applyStage != '' && baseForm.value.standardProjectInfo.applyStage != '0')
)
const shenheDisabled = computed(() => props.isView)
const shenbaoDdfUploadDisabled = computed(() => props.isView || Number(baseForm.value.standardProjectInfo.applyStage) > 1)

const emit = defineEmits(['update:modelValue', 'submit-success', 'dialog-cancel'])

const activeName = ref('base')
const baseFormRef = ref<FormInstance>()
const baseForm = ref({
	standardProjectInfo: {
		id: '',
		standardProjectName: '',
		applyYear: '',
		projectSelfFunding: '',
		projectFunding: '',
		responsibleOrg: '',
		contactName: '',
		contactTel: '',
		contactAddress: '',
		contactEmail: '',
		professionalKeyFields: '',
		applyStage: ''
	},
	standardProjectProposal: {
		id: '',
		standardCategory: '0',
		standardType: '0',
		originalNumber: '',
		setGoal: '',
		standardRelationship: '',
		standardComparison: '',
		integrateSuggestions: '',
		scopeApplication: '',
		mainContent: '',
		keyTechnology: '',
		preparationSchedule: '',
		editorUnitWorkSituation: '',
		responsiblePersonWorkSituation: '',
		remark: '',
		isUploadPdf: 1
	},
	projectEditorUnitList: [] as Unit[],
	projectMainDrafterList: [] as Drafter[],
	filesRecordList: [] as UploadFile[],
	projectDocument: [] as UploadFile[]
})

const rules = reactive<any>({})
const baseRules = computed(() => ({
	standardProjectInfo: {
		standardProjectName: [{ required: true, message: '请输入', trigger: 'blur' }],
		applyYear: [{ required: true, message: '请选择', trigger: 'change' }],
		projectSelfFunding: [
			{ required: true, message: '请输入', trigger: 'blur' },
			{
				pattern: /^-?\d+(\.\d+)?$/,
				message: '请输入有效的数字',
				trigger: 'blur'
			}
		],
		projectFunding: [
			{ required: true, message: '请输入', trigger: 'blur' },
			{
				pattern: /^-?\d+(\.\d+)?$/,
				message: '请输入有效的数字',
				trigger: 'blur'
			}
		],
		responsibleOrg: [{ required: true, message: '请选择', trigger: 'change' }],
		contactName: [{ required: true, message: '请输入', trigger: 'blur' }],
		contactTel: [
			{ required: true, message: '请输入', trigger: 'blur' },
			{ pattern: /^1\d{10}$/, message: '请输入有效的手机号', trigger: 'blur' }
		],
		contactAddress: [{ required: true, message: '请输入', trigger: 'blur' }],
		contactEmail: [
			{ required: true, message: '请输入', trigger: 'blur' },
			{
				pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
				message: '请输入有效的邮箱地址',
				trigger: 'blur'
			}
		],
		professionalKeyFields: [{ required: true, message: '请选择', trigger: 'change' }]
	},
	standardProjectProposal: {
		standardCategory: [{ required: true, message: '请选择', trigger: 'change' }],
		originalNumber: [{ required: baseForm.value.standardProjectProposal.standardCategory == '1', message: '请输入', trigger: 'blur' }],
		standardType: [{ required: true, message: '请选择', trigger: 'change' }],
		setGoal: [{ required: true, message: '请输入', trigger: 'blur' }],
		standardRelationship: [
			{ required: true, message: '请输入', trigger: 'blur' },
			{ min: 1, max: 500, message: '不能超过500字', trigger: 'blur' }
		],
		standardComparison: [
			{ required: true, message: '请输入', trigger: 'blur' },
			{ min: 1, max: 500, message: '不能超过500字', trigger: 'blur' }
		],
		scopeApplication: [
			{ required: true, message: '请输入', trigger: 'blur' },
			{ min: 1, max: 500, message: '不能超过500字', trigger: 'blur' }
		],
		mainContent: [
			{ required: true, message: '请输入', trigger: 'blur' },
			{ min: 1, max: 500, message: '不能超过500字', trigger: 'blur' }
		],
		keyTechnology: [
			{ required: true, message: '请输入', trigger: 'blur' },
			{ min: 1, max: 500, message: '不能超过500字', trigger: 'blur' }
		],
		preparationSchedule: [
			{ required: true, message: '请输入', trigger: 'blur' },
			{ min: 1, max: 500, message: '不能超过500字', trigger: 'blur' }
		],
		editorUnitWorkSituation: [
			{ required: true, message: '请输入', trigger: 'blur' },
			{ min: 1, max: 500, message: '不能超过500字', trigger: 'blur' }
		],
		responsiblePersonWorkSituation: [
			{ required: true, message: '请输入', trigger: 'blur' },
			{ min: 1, max: 500, message: '不能超过500字', trigger: 'blur' }
		],
		integrateSuggestions: [{ min: 1, max: 500, message: '不能超过500字', trigger: 'blur' }]
	},
	pdfFile1: [
		{
			required: true
		}
	],
	pdfFile2: [
		{
			required: true
		}
	]
}))
const unitList = ref<Unit[]>([])
const showAddUnit = ref(false)
const unitInfo = ref<Unit>({
	orderName: 1,
	editorUnitName: '',
	contacts: '',
	contactsTel: '',
	contactsEmail: '',
	contactsAddress: '',
	responsiblePerson: '',
	responsiblePersonTel: '',
	responsiblePersonEmail: '',
	userCode: '',
	remark: '',
	unitType: 0,
	index: -1
})
const drafterList = ref<Drafter[]>([])
const showAddDrafter = ref(false)
const drafterInfo = ref<Drafter>({
	mainDrafterName: '',
	mainDrafterTitle: '',
	mainDrafterCompany: '',
	responsibleContent: '',
	drafterRemark: '',
	remark: '',
	// submitApprovalDelete: 1,
	index: -1
})
const unitCount = ref(0)
const uploadApi = `${import.meta.env.MODE === 'development' ? 'http://220.196.89.86:9173' : window.location.protocol + '//' + window.location.host}/JGBStandardWebApi/api/files/upload`
const uploadHeaders = {
	Authorization: userStore.token
}
const uploadData = {
	extCode: 'ProjectProposalStampedVersion',
	remark: '项目建议书盖章版(pdf)'
}
const uploadData2 = {
	extCode: 'StandardApplyOtherFiles',
	remark: '项目建议书其他资料'
}
const uploadData3 = {
	extCode: 'AchievementMaterials',
	remark: '成果资料'
}
// const uploadPdf =

const uploadPdfRef = ref<UploadInstance>()
const uploadPdf1Ref = ref<UploadInstance>()
const uploadPdfList = ref<UploadFile[]>([])
const uploadPdfList1 = ref<UploadFile[]>([])
const uploadList = ref<UploadFile[]>([])
const uploadShowPdfList = ref<UploadRawFile[]>([])
const uploadShowPdfList1 = ref<UploadRawFile[]>([])
const uploadShowList = ref<UploadRawFile[]>([])

const responsibleOrgArr = ref([])
// const subResponsibleOrgArr = dictionaryStore.getDictionaryByCode('T0030')
const professionalKeyFieldsArr = dictionaryStore.getDictionaryByCode('T003')
const standardCategory = dictionaryStore.getDictionaryByCode('T005')
const standardType = dictionaryStore.getDictionaryByCode('T006')
// const applyResult = dictionaryStore.getDictionaryByCode('T013')

const auditRecordList = ref([])

const codeMap = {
	'1': 'ZGBM_Approve',
	'2': 'XMHZ_Approve',
	'3': 'ZJPS_Approve',
	'4': 'ZZSH_Approve',
	'5': 'ZJWSH_Approve'
}

const dialogState = computed({
	get: () => props.modelValue,
	set: val => emit('update:modelValue', val)
})

watch(
	() => props.editId,
	newVal => {
		if (newVal) {
			getDeclare({
				id: newVal
			}).then(res => {
				let data = res.data
				data.standardProjectInfo.professionalKeyFields = data.standardProjectInfo.professionalKeyFields
					? data.standardProjectInfo.professionalKeyFields.split(',')
					: ''
				data.standardProjectInfo.responsibleOrg = data.standardProjectInfo.responsibleOrg ? data.standardProjectInfo.responsibleOrg.split(',') : ''
				baseForm.value = data
				unitList.value = []
				data.projectEditorUnitList.forEach((i: any, index: number) => {
					unitList.value.push({
						id: i.id,
						orderName: index + 1,
						editorUnitName: i.editorUnitName,
						contacts: i.contacts,
						contactsTel: i.contactsTel,
						contactsEmail: i.contactsEmail,
						contactsAddress: i.contactsAddress,
						responsiblePerson: i.responsiblePerson,
						responsiblePersonTel: i.responsiblePersonTel,
						responsiblePersonEmail: i.responsiblePersonEmail,
						userCode: i.userCode,
						remark: i.remark,
						unitType: i.unitType,
						index: index
					})
				})
				drafterList.value = []
				data.projectMainDrafterList.forEach((i: any, index: number) => {
					drafterList.value.push({
						id: i.id,
						mainDrafterName: i.mainDrafterName,
						mainDrafterTitle: i.mainDrafterTitle,
						mainDrafterCompany: i.mainDrafterCompany,
						responsibleContent: i.responsibleContent,
						drafterRemark: i.drafterRemark,
						remark: i.remark,
						index: index
					})
				})
				uploadPdfList.value = data.filesRecordList.filter((i: any) => i.extCode === 'ProjectProposalStampedVersion') || []
				uploadPdfList1.value = data.filesRecordList.filter((i: any) => i.extCode === 'AchievementMaterials') || []
				uploadList.value = data.filesRecordList.filter((i: any) => i.extCode === 'StandardApplyOtherFiles') || []
				uploadShowPdfList.value = JSON.parse(JSON.stringify(uploadPdfList.value))
				uploadShowPdfList1.value = JSON.parse(JSON.stringify(uploadPdfList1.value))
				uploadShowList.value = JSON.parse(JSON.stringify(uploadList.value))
				if (uploadShowPdfList.value.length > 0) {
					uploadShowPdfList.value.forEach((i: any) => {
						i.name = i.fileRealName
					})
				}
				if (uploadShowPdfList1.value.length > 0) {
					uploadShowPdfList1.value.forEach((i: any) => {
						i.name = i.fileRealName
					})
				}
				if (uploadShowList.value.length > 0) {
					uploadShowList.value.forEach((i: any) => {
						i.name = i.fileRealName
					})
				}
				auditRecordList.value = data.auditRecordList
			})
		} else {
			baseFormRef.value?.resetFields()
			unitList.value = []
			drafterList.value = []
			uploadPdfList.value = []
			uploadPdfList1.value = []
			uploadList.value = []
			uploadShowPdfList.value = []
			uploadShowPdfList1.value = []
			uploadShowList.value = []
			baseForm.value.standardProjectInfo.id = ''
			baseForm.value.standardProjectInfo.applyStage = ''
			baseForm.value.standardProjectProposal.id = ''
			baseForm.value.projectEditorUnitList = []
			baseForm.value.projectMainDrafterList = []
			baseForm.value.filesRecordList = []
		}
	},
	{ immediate: true }
)

watch(
	() => props.modelValue,
	newVal => {
		if (!newVal) {
			activeName.value = 'base'
		}
	}
)

const handleExceed: UploadProps['onExceed'] = files => {
	ElMessageBox.confirm('只能上传一份文件，若要替换，请先删除已有文件', '温馨提示', {
		showConfirmButton: false,
		cancelButtonText: '知道了',
		type: 'warning'
	})
}

const handleUploadPdfPreview = (ruploadFile: any) => {
	if (ruploadFile.systemFileName) {
		filePreviewByName(ruploadFile.systemFileName).then(res => {
			window.open(res.data.url)
		})
	} else {
		filePreviewByName(ruploadFile?.response.data.systemFileName).then(res => {
			window.open(res.data.url)
		})
	}
}

const handleUploadPdfSuccess = (res: any, uploadFile: UploadRawFile) => {
	if (res.code == '200') {
		uploadPdfList.value = []
		uploadPdfList.value.push(res.data)
		saveTemp(2)
	} else {
		handleUploadPdfError(res, uploadFile)
	}
}

const handleUploadPdfSuccess1 = (res: any, uploadFile: UploadRawFile) => {
	if (res.code == '200') {
		uploadPdfList1.value = []
		uploadPdfList1.value.push(res.data)
		saveTemp(2)
	} else {
		handleUploadPdfError1(res, uploadFile)
	}
}

const beforeUploadPdf = (file: UploadRawFile) => {
	const allowedTypes = ['application/pdf']
	const fileExtension = file.name.split('.').pop()?.toLowerCase()
	if (!allowedTypes.includes(file.type) || fileExtension !== 'pdf') {
		ElMessage.error('仅支持上传 PDF 文件')
		return false
	}
	return true
}

const handleUploadPdfRemove = (file: UploadRawFile) => {
	uploadPdfList.value = []
	saveTemp(2)
}

const handleUploadPdfRemove1 = (file: UploadRawFile) => {
	uploadPdfList1.value = []
	saveTemp(2)
}

const handleUploadPdfError = (error: Error, uploadFile: UploadRawFile) => {
	ElMessage.error(error.message)
	uploadShowPdfList.value = uploadShowPdfList.value.filter((item: UploadRawFile) => item.uid !== uploadFile.uid)
}
const handleUploadPdfError1 = (error: Error, uploadFile: UploadRawFile) => {
	ElMessage.error(error.message)
	uploadShowPdfList1.value = uploadShowPdfList1.value.filter((item: UploadRawFile) => item.uid !== uploadFile.uid)
}

const handleUploadSuccess = (res: any, uploadFile: UploadRawFile) => {
	if (res.code == '200') {
		uploadList.value.push(res.data)
		saveTemp(2)
	} else {
		handleUploadError(res, uploadFile)
	}
}

const handleUploadRemove = (file: any) => {
	const id = file.response ? file.response.data.id : file.id
	uploadList.value = uploadList.value.filter((item: UploadFile) => item.id !== id)
	saveTemp(2)
}

const handleUploadError = (error: Error, uploadFile: UploadRawFile) => {
	ElMessage.error(error.message)
	uploadShowList.value = uploadShowList.value.filter((item: UploadRawFile) => item.uid !== uploadFile.uid)
}

const handleClick = (tab: TabsPaneContext, event: Event) => {
	// console.log(tab, event)
}

const closeModal = () => {
	emit('update:modelValue', false)
}

const handleAddUnit = () => {
	unitCount.value = unitList.value.length
	const mainUnitCount = unitList.value.filter(unit => unit.unitType == 0).length
	if (mainUnitCount >= 2) {
		ElMessageBox.confirm('根据编制要求主编单位原则上不超过2家！', '温馨提示', {
			confirmButtonText: '继续增加',
			cancelButtonText: '关闭',
			type: 'warning'
		})
			.then(() => {
				showAddUnit.value = true
			})
			.catch(() => {})
	} else {
		showAddUnit.value = true
	}
}

const handleAddDrafter = () => {
	if (drafterList.value.length >= 25) {
		ElMessageBox.confirm('根据编制要求，起草人原则上不超过25个！', '温馨提示', {
			confirmButtonText: '继续增加',
			cancelButtonText: '关闭',
			type: 'warning'
		})
			.then(() => {
				showAddDrafter.value = true
			})
			.catch(() => {})
	} else {
		showAddDrafter.value = true
	}
}

const submitUnit = (e: Unit) => {
	showAddUnit.value = false
	const index = e.index ?? -1
	if (index > -1) {
		unitList.value[index] = e
	} else {
		unitList.value.push({ ...e })
	}
}

const handleEditUnit = (e: Unit, i: number) => {
	showAddUnit.value = true
	e.index = i
	unitInfo.value = e
}

const handleDeleteUnit = (i: number) => {
	ElMessageBox.confirm('确定要删除吗?', '提示', {
		confirmButtonText: '删除',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(() => {
		unitList.value.splice(i, 1)
	})
}

const submitDrafter = (e: Drafter) => {
	showAddDrafter.value = false
	const index = e.index ?? -1
	if (index > -1) {
		drafterList.value[index] = e
	} else {
		drafterList.value.push({ ...e })
	}
}

const closeUnitDialog = () => {
	activeName.value = 'base'
	unitCount.value = 0
	unitInfo.value = {
		orderName: 1,
		editorUnitName: '',
		contacts: '',
		contactsTel: '',
		contactsEmail: '',
		contactsAddress: '',
		responsiblePerson: '',
		responsiblePersonTel: '',
		responsiblePersonEmail: '',
		userCode: '',
		remark: '',
		unitType: 0,
		index: -1
	}
}

const closeDrafterDialog = () => {
	drafterInfo.value = {
		mainDrafterName: '',
		mainDrafterTitle: '',
		mainDrafterCompany: '',
		responsibleContent: '',
		drafterRemark: '',
		remark: '',
		// submitApprovalDelete: 1,
		index: -1
	}
}

const handleEditDrafter = (e: Drafter, i: number) => {
	showAddDrafter.value = true
	e.index = i
	drafterInfo.value = e
}

const handleDeleteDrafter = (i: number) => {
	ElMessageBox.confirm('确定要删除吗?', '提示', {
		confirmButtonText: '删除',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(() => {
		drafterList.value.splice(i, 1)
	})
}

const saveTemp = (type = 1) => {
	if (!baseForm.value.standardProjectInfo.id && type == 2) {
		return
	}
	let form = JSON.parse(JSON.stringify(baseForm.value))
	form.standardProjectInfo.professionalKeyFields = form.standardProjectInfo.professionalKeyFields.toString()
	form.standardProjectInfo.responsibleOrg = form.standardProjectInfo.responsibleOrg.toString()
	const cleanedUnitList = unitList.value.map(({ index, ...rest }) => rest)
	form.projectEditorUnitList = cleanedUnitList
	const cleanedDrafterList = drafterList.value.map(({ index, ...rest }) => rest)
	form.projectMainDrafterList = cleanedDrafterList
	form.filesRecordList = []
	form.filesRecordList.push(...uploadPdfList.value, ...uploadPdfList1.value, ...uploadList.value)
	if ('auditRecordList' in form) {
		delete (form as any).auditRecordList
	}
	delete (form as any).projectDocument
	const api = props.editId ? updateDeclareTemp : addDeclareTemp
	api(form).then(res => {
		if (type == 1) {
			baseFormRef.value?.resetFields()
			emit('submit-success', res.data)
		}
	})
}

const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) {
		return
	}
	const mainUnitCount = unitList.value.filter(unit => unit.unitType == 0).length
	if (mainUnitCount == 0) {
		ElMessage.error('主编单位至少填写一家！')
		activeName.value = 'base'
		return
	}
	if (drafterList.value.length < 1) {
		ElMessage.error('请至少填写一位起草人！')
		if (activeName.value != 'input') {
			activeName.value = 'input'
		}
		return
	}
	if (uploadPdfList.value.length == 0) {
		ElMessage.error('请上传项目建议书盖章版PDF文件！')
		if (activeName.value != 'upload') {
			activeName.value = 'upload'
		}
		return
	}
	if (uploadPdfList1.value.length == 0) {
		ElMessage.error('请上传成果资料PDF文件！')
		if (activeName.value != 'upload') {
			activeName.value = 'upload'
		}
		return
	}
	await formEl.validate((valid, fields) => {
		if (valid) {
			let form = { ...baseForm.value }
			form.standardProjectInfo.professionalKeyFields = form.standardProjectInfo.professionalKeyFields.toString()
			form.standardProjectInfo.responsibleOrg = form.standardProjectInfo.responsibleOrg.toString()
			const cleanedUnitList = unitList.value.map(({ index, ...rest }) => rest)
			form.projectEditorUnitList = cleanedUnitList
			const cleanedDrafterList = drafterList.value.map(({ index, ...rest }) => rest)
			form.projectMainDrafterList = cleanedDrafterList
			form.filesRecordList = []
			form.filesRecordList.push(...uploadPdfList.value, ...uploadPdfList1.value, ...uploadList.value)
			if ('auditRecordList' in form) {
				delete (form as any).auditRecordList
			}
			delete (form as any).projectDocument
			const api = props.isAudit ? updateDeclareTemp : saveDeclare
			api(form).then(res => {
				ElMessage.success('操作成功！')
				baseFormRef.value?.resetFields()
				emit('submit-success', res.data)
			})
		} else {
			if (!fields) {
				return
			}
			console.log(Object.keys(fields)[0])
			const firstErrorField = Object.keys(fields)[0]
			if (firstErrorField.startsWith('standardProjectInfo.')) {
				activeName.value = 'base'
			}
		}
	})
}

const saveUploadPdf = () => {
	if (uploadPdfList.value.length == 0) {
		ElMessage.error('请上传项目建议书盖章版PDF文件！')
		return
	}
	if (uploadPdfList1.value.length == 0) {
		ElMessage.error('请上传成果资料PDF文件！')
		return
	}
	let form = { ...baseForm.value }
	form.standardProjectInfo.professionalKeyFields = form.standardProjectInfo.professionalKeyFields.toString()
	form.standardProjectInfo.responsibleOrg = form.standardProjectInfo.responsibleOrg.toString()
	const cleanedUnitList = unitList.value.map(({ index, ...rest }) => rest)
	form.projectEditorUnitList = cleanedUnitList
	const cleanedDrafterList = drafterList.value.map(({ index, ...rest }) => rest)
	form.projectMainDrafterList = cleanedDrafterList
	form.filesRecordList = []
	form.filesRecordList.push(...uploadPdfList.value, ...uploadPdfList1.value, ...uploadList.value)
	if ('auditRecordList' in form) {
		delete (form as any).auditRecordList
	}
	delete (form as any).projectDocument
	const api = props.editId ? updateDeclareTemp : addDeclareTemp
	api(form).then(res => {
		baseFormRef.value?.resetFields()
		emit('submit-success', res.data)
	})
}

onMounted(() => {
	responsibleOrgArr.value = dictionaryStore.getDictionaryByCode('T002')
	responsibleOrgArr.value.forEach(item => {
		if (item.id == '9') {
			item.children = dictionaryStore.getDictionaryByCode('T0030')
		}
	})
})
</script>
<style lang="scss" scoped>
.tabs :deep(.el-tabs__nav-wrap) {
	display: flex;
	justify-content: center;
	margin-top: 10px;
}

.content {
	padding: 0 20px;

	.add-unit {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-top: 20px;
		border-top: solid 1px #eee;
		margin-bottom: 10px;

		.tit {
			font-size: 14px;
			color: #333;
		}
	}
}

.dialog-foot {
	display: flex;
	justify-content: center;
	margin-bottom: 10px;
	padding-bottom: 20px;
}

:deep(.el-form-item__label) {
	line-height: 1.5;
}

:deep(.custom-label .el-form-item__label) {
	line-height: 32px;
}

.upload-item {
	:deep(.el-form-item__label) {
		&::before {
			content: '*';
			color: red;
			margin-right: 5px;
		}
	}
}
</style>
